<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>关于 Rust 的 UnsafeCell、Cell 与 RefCell - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html" class="active"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="关于-rust-的-unsafecellcell-与-refcell"><a class="header" href="#关于-rust-的-unsafecellcell-与-refcell">关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></h1>
<p>原载：<a href="https://zhuanlan.zhihu.com/p/598708941">https://zhuanlan.zhihu.com/p/598708941</a></p>
<p>作者：<a href="https://www.zhihu.com/people/yi-ci-yuan-33-29">异次元</a></p>
<p>Rust 标准库有些代码实现虽然简单，比如<code>UnsafeCell</code>、<code>Cell</code>，但是里面的代码都经过了<strong>精心的设计</strong></p>
<p>有些代码差别很微妙，但是影响十分的大，包括但不限于：方法接口的设计、<code>unsafe</code>修饰、<code>trait</code> 实现的限定，如果不仔细，就很注意不到</p>
<h3 id="unsafecell"><a class="header" href="#unsafecell">UnsafeCell</a></h3>
<p><code>UnsafeCell</code> 代码很简单，只是简单包裹 <code>T</code>，<code>T</code>泛型可以是任意类型</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[lang = &quot;unsafe_cell&quot;]
#[repr(transparent)]
pub struct UnsafeCell&lt;T: ?Sized&gt; {
    value: T,
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="unsafecell-核心方法"><a class="header" href="#unsafecell-核心方法">UnsafeCell 核心方法</a></h3>
<p><code>UnsafeCell</code>有一个重要的<code>get</code>方法，此方法能够通过<strong>不可变引用</strong>（<code>&amp;T</code>），获取到了<strong>可变裸指针</strong> (<code>*mut T</code>)，它是通过强转来实现的，强转到裸指针是<strong>安全的</strong>，你需要注意的是<strong>正确的对它进行解引用</strong></p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub const fn get(&amp;self) -&gt; *mut T {
   self as *const UnsafeCell&lt;T&gt; as *const T as *mut T
}
<span class="boring">}
</span></code></pre></pre>
<p><code>*const UnsafeCell&lt;T&gt;</code>为什么可以转为<code>*const T</code>？</p>
<pre><code>UnsafeCell`使用了`#[repr(transparent)]`属性宏，显示指定了`UnsafeCell&lt;T&gt;`内存结构必须与`T`相同，所以完全可以转换`UnsafeCell&lt;T&gt;`到`T
</code></pre>
<blockquote>
<p>注意：
<code>*const UnsafeCell&lt;T&gt; as *mut T</code> 在<strong>用户代码中</strong>是<strong>未定义的行为</strong>，即使拥有相同的布局，而<code>#&gt;[repr(transparent)]</code>利用了<code>std</code>标准库的特殊性，能够保证它是安全的，但它没有保证用户代码在未来版本也能正常工作，所以你不要自己去转换，而是使用<code>UnsafeCell</code>的<code>get</code>或者<code>raw_get</code>。
而反过来转换，即<code>*mut T as *const UnsafeCell&lt;T&gt;</code>在用户代码中也是是安全的</p>
</blockquote>
<h3 id="unsafecell-是安全的"><a class="header" href="#unsafecell-是安全的">UnsafeCell 是安全的</a></h3>
<p><code>UnsafeCell</code>从名字看是不安全的，实际上它是<strong>安全的</strong>，因为它的方法<strong>全都没有用<code>unsafe</code>修饰</strong>，只是它的核心方法<code>get</code>返回的是<strong>可变裸指针</strong>，创建裸指针<strong>是安全的</strong>，<strong>解引用裸指针才是不安全的</strong>。</p>
<p>示例如下，下面代码不需要使用<code>unsafe</code>：</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::UnsafeCell;
// 
fn main() {
    let cell = UnsafeCell::new(12);
    println!(&quot;{:?}&quot;, cell.get());
}
</code></pre></pre>
<p>那么它 “不安全” 在哪 ？</p>
<pre><code>UnsafeCell`返回了可变裸指针，这影响了共享引用的不变性保证，但是可变引用的唯一性保证不受影响，你没有合法的方法获得别名`&amp;mut
</code></pre>
<p>裸指针是危险的，你需要去正确的对它解引用，所以在 rust 中解引用是不安全的，需要你用<code>unsafe</code>进行包裹</p>
<p>裸指针没有借用和生命周期的检查，这需要你自己去注意它的生命周期与读写冲突</p>
<h3 id="unsafecell-其他方法"><a class="header" href="#unsafecell-其他方法">UnsafeCell 其他方法</a></h3>
<p>这些方法用于暴露内部<code>value</code>，没什么特别</p>
<p><code>into_inner</code>方法，转移自身<code>T</code>的所以权</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub const fn into_inner(self) -&gt; T { self.value }
get_mut`方法，通过`&amp;mut self`获取`&amp;mut T
pub const fn get_mut(&amp;mut self) -&gt; &amp;mut T { &amp;mut self.value }
<span class="boring">}
</span></code></pre></pre>
<h3 id="编译器对-unsafecell-的特殊处理"><a class="header" href="#编译器对-unsafecell-的特殊处理">编译器对 UnsafeCell 的特殊处理</a></h3>
<blockquote>
<p>关于 rust 子类型、泛变 ，参考：<a href="https://link.zhihu.com/?target=https%3A//doc.rust-lang.org/nomicon/subtyping.html">https://doc.rust-lang.org/nomicon/subtyping.html</a></p>
</blockquote>
<p><code>UnsafeCell</code>使用了<code>#[lang = &quot;unsafe_cell&quot;]</code>属性宏，这表示编译器需要对<code>UnsafeCell</code>进行特殊处理</p>
<p>那么编译器对它做了什么特殊处理？</p>
<p>编译器使得<code>UnsafeCell</code>对生命周期参数没有<strong>协/逆变</strong>特性，也就是说它是<strong>不变</strong>的</p>
<p>看下面示例，我定义了<code>MyUnsafeCell</code>,它和<code>UnsafeCell</code>有一样的结构，它可以对生命周期参数进行协变，但是<code>UnsafeCell</code>不能：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn test_cell&lt;'long: 'short, 'short&gt;(mut cell: UnsafeCell&lt;&amp;'short i32&gt;, cell2: UnsafeCell&lt;&amp;'long i32&gt;) {
    cell = cell2; // 错误！UnsafeCell 生命周期参数不能协变
}


#[repr(transparent)]
pub struct MyUnsafeCell&lt;T: ?Sized&gt; {
    value: T,
}

fn test_my_cell&lt;'long: 'short, 'short&gt;(mut cell: MyUnsafeCell&lt;&amp;'short i32&gt;, cell2: MyUnsafeCell&lt;&amp;'long i32&gt;) {
    cell = cell2; // 无错误
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="为什么unsafecell不能对生命周期参数进行协变"><a class="header" href="#为什么unsafecell不能对生命周期参数进行协变">为什么<code>UnsafeCell</code>不能对生命周期参数进行协变？</a></h3>
<blockquote>
<p>如果你还不了解 Cell，你可以先看后面的对 Cell 的介绍</p>
</blockquote>
<p>如果允许协变会怎样？为了说明 允许协变 将会造成的问题</p>
<p>下面我们仿照<code>UnsafeCell</code>与<code>Cell</code>，定义自己的<code>MyUnsafeCell</code>与<code>MyCell</code>，与官方唯一实现区别就是我们自己定义的<code>MyUnsafeCell</code>能够对生命周期参数进行协变</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::mem;

pub struct MyUnsafeCell&lt;T: ?Sized&gt; {
    value: T,
}
impl&lt;T&gt; MyUnsafeCell&lt;T&gt; {
    pub const fn new(value: T) -&gt; MyUnsafeCell&lt;T&gt; {
        MyUnsafeCell { value }
    }
}
impl&lt;T: ?Sized&gt; MyUnsafeCell&lt;T&gt; {
    pub const fn get(&amp;self) -&gt; *mut T {
        self as *const MyUnsafeCell&lt;T&gt; as *const T as *mut T
    }
}

pub struct MyCell&lt;T: ?Sized&gt; {
    value: MyUnsafeCell&lt;T&gt;,
}

impl&lt;T&gt; MyCell&lt;T&gt; {
    pub fn new(value: T) -&gt; Self {
        Self {
            value: MyUnsafeCell::new(value),
        }
    }

    pub fn set(&amp;self, val: T) {
        let _ = mem::replace(unsafe { &amp;mut *self.value.get() }, val);
    }

    pub fn get(&amp;self) -&gt; T
    where
        T: Copy,
    {
        unsafe { *self.value.get() }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>下面是 <code>MyCell&lt;T&gt;</code>中<code>T</code>是一个引用，并且使用协变 的一个例子</p>
<pre><pre class="playground"><code class="language-rust">fn test_set&lt;'long, 'short&gt;(cell: &amp;MyCell&lt;&amp;'long isize&gt;, value: &amp;'short isize)
where
    'long: 'short,
{
    let cell: &amp;MyCell&lt;&amp;'short isize&gt; = cell; // 此处发生了协变，长生命周期Cell 赋值给 短生命周期 Cell
    cell.set(value);
}

fn main() {
    let local = 1;
    let cell = MyCell::new(&amp;local);
    {
        let local2 = 21;
        test_set(&amp;cell, &amp;local2);
    }

    let p = cell.get();
    println!(&quot;{}&quot;, p);
}
</code></pre></pre>
<p>你会发现它能够编译成功，但是很明显，<code>local2</code>已经离开作用域并被销毁，但是<code>cell</code>却还引用了<code>local2</code>，此时出现了悬空指针！<code>cargo run --release</code>去运行时（注意需要是 <code>release</code>），结果会打印一段随机的数字</p>
<p>如果将<code>MyCell</code>换成官方的<code>Cell</code>，编译将不会成功，原因你应该已经知道，官方<code>Cell</code>使用了<code>UnsafeCell</code>，编译器对<code>UnsafeCell</code>做了特殊处理，让<code>UnsafeCell</code>不能对生命周期参数进行协变，</p>
<h3 id="unsafecell-与内部可变性"><a class="header" href="#unsafecell-与内部可变性">UnsafeCell 与内部可变性</a></h3>
<p>如果你要自己实现内部可变性，那么你<strong>必须</strong>使用<code>UnsafeCell</code>，不这么做是未定义行为，不要自己通过<code>transmute</code>等手段强转为可变引用</p>
<p>因为你没办法处理生命周期问题</p>
<h3 id="总结"><a class="header" href="#总结">总结</a></h3>
<ul>
<li><code>UnsafeCell</code>无额外开销</li>
<li><code>UnsafeCell</code>实现了从不可变引用到<strong>可变裸指针</strong>的转换</li>
<li>编译器对<code>UnsafeCell</code>的生命周期泛型做了特殊处理</li>
<li>使用 <code>UnsafeCell</code> 去实现部可变性，而不是自己通过<code>transmute</code>等手段强转</li>
</ul>
<h3 id="cell"><a class="header" href="#cell">Cell</a></h3>
<p><code>Cell&lt;T&gt;</code> 实现了单线程下的内部可变性，适合用于<code>Copy</code>类型</p>
<p><code>Cell&lt;T&gt;</code> 代码也很简单，只是包裹了<code>UnsafeCell&lt;T&gt;</code>，也有<code>#[repr(transparent)]</code>，所以内存结构与<code>T</code>也是一样的</p>
<p><code>Cell&lt;T&gt;</code> 没有额外的性能损耗</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[repr(transparent)]
pub struct Cell&lt;T: ?Sized&gt; {
    value: UnsafeCell&lt;T&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p><code>Cell&lt;T&gt;</code> 暴露修改方法只能你去<strong>完整设置自身</strong>，也就是<code>T</code>，无法单独修改<code>T</code>的字段，这个设计保证了它的安全</p>
<p>由于它只能<strong>完整设置自身</strong>，所以比较适合<code>Copy</code>类型</p>
<h3 id="cell-核心方法"><a class="header" href="#cell-核心方法">Cell 核心方法</a></h3>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T&gt; Cell&lt;T&gt; {
   pub fn set(&amp;self, val: T) {
      let old = self.replace(val);
      drop(old);
   }
   pub fn replace(&amp;self, val: T) -&gt; T {
      mem::replace(unsafe { &amp;mut *self.value.get() }, val)
   }
}
<span class="boring">}
</span></code></pre></pre>
<p><code>Cell</code> 通过<code>UnsafeCell</code>提供的<code>get</code>方法获取裸指针，再通过<code>&amp;mut *</code>转换为可变引用，再调用<code>mem::replace</code>替换整个值来进行设置</p>
<p>用例：</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::Cell;
fn main() {
    let cell = Cell::new(true);
    let cell_ref1 = &amp;cell;
    let cell_ref2 = &amp;cell;
    cell_ref1.set(false);
    cell_ref2.set(true);
}
</code></pre></pre>
<h3 id="cell-其他方法"><a class="header" href="#cell-其他方法">Cell 其他方法</a></h3>
<p><code>Cell</code> 还提供了<code>swap</code>、<code>take</code>方法，他们与<code>mem</code>模块下的同名方法提供类似功能</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T&gt; Cell&lt;T&gt; {
   pub fn swap(&amp;self, other: &amp;Self) {
      if ptr::eq(self, other) {
         return;
      }
      unsafe {
         ptr::swap(self.value.get(), other.value.get());
      }
   }
}

impl&lt;T: Default&gt; Cell&lt;T&gt; {
    pub fn take(&amp;self) -&gt; T {
        self.replace(Default::default())
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="cell-为什么提供获取可变引用的方法却不提供获取引用的方法"><a class="header" href="#cell-为什么提供获取可变引用的方法却不提供获取引用的方法">Cell 为什么提供获取可变引用的方法，却不提供获取引用的方法？</a></h3>
<blockquote>
<p>参考：<a href="https://link.zhihu.com/?target=https%3A//www.reddit.com/r/rust/comments/kvdnil/question_why_stdcellcellt_dont_have_get_ref_but/">https://www.reddit.com/r/rust/comments/kvdnil/question_why_stdcellcellt_dont_have_get_ref_but/</a></p>
</blockquote>
<p>与<code>UnsafeCell&lt;T&gt;</code>一样，<code>Cell&lt;T&gt;</code>也提供<code>get_mut</code>方法</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn get_mut(&amp;mut self) -&gt; &amp;mut T { self.value.get_mut() }
<span class="boring">}
</span></code></pre></pre>
<p>在不转移所有权的情况下，我们只能通过<code>get_mut</code>去访问<code>T</code></p>
<pre><pre class="playground"><code class="language-rust">#[derive(Debug)]
pub struct Foo {
    a: u32,
}
fn main() {
    let mut cell = Cell::new(Foo { a: 12 });
    let x = cell.get_mut();
    println!(&quot;{:?}&quot;, x);
}
</code></pre></pre>
<p>既然提供了<code>get_mut</code>方法，但是为什么没有提供获取<code>&amp;T</code>的方法？</p>
<p>如果提供了获取<code>&amp;T</code>的方法，并不能保证借用的<code>T</code>不发生改变，<code>Cell</code>可以随时通过<code>set</code>更改自身，这与不可变引用语义不符，而且也会引发bug，原因等下之后会进行说明</p>
<h3 id="通过-cell-解决-迭代中进行修改-的借用检查问题"><a class="header" href="#通过-cell-解决-迭代中进行修改-的借用检查问题">通过 Cell 解决 &quot;迭代中进行修改&quot; 的借用检查问题</a></h3>
<blockquote>
<p>参考：<a href="https://link.zhihu.com/?target=https%3A//ryhl.io/blog/temporary-shared-mutation/">https://ryhl.io/blog/temporary-shared-mutation/</a></p>
</blockquote>
<p><code>Cell</code>还提供了以下方法</p>
<ul>
<li><code>Cell::from_mut</code>：用于将<code>&amp;mut T</code> 转为 <code>&amp;Cell&lt;T&gt;</code>，<code>Cell&lt;T&gt;</code>内存布局与<code>T</code>是一样的，所以可以进行转换，</li>
<li><code>Cell::as_slice_of_cells</code>：用于将 <code>&amp;Cell&lt;[T]&gt;</code> 转为 <code>&amp;[Cell&lt;T&gt;]</code></li>
</ul>
<p>解决借用冲突的用例：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn retain_even(nums: &amp;mut Vec&lt;i32&gt;) {
    let mut i = 0;
    for num in nums.iter().filter(|&amp;num| is_even(*num)) {
        nums[i] = *num;
        i += 1;
    }
    nums.truncate(i);
}
<span class="boring">}
</span></code></pre></pre>
<p>因为同时借用了不可变与可变引用，所以以上代码会报错：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>error[E0502]: cannot borrow `*nums` as mutable because it is also borrowed as immutable
 --&gt; src/lib.rs:4:9
  |
3 |     for num in nums.iter().filter(|&amp;num| is_even(*num)) {
  |                ----------------------------------------
  |                |
  |                immutable borrow occurs here
  |                immutable borrow later used here
4 |         nums[i] = *num;
  |         ^^^^ mutable borrow occurs here

error: aborting due to previous error
<span class="boring">}
</span></code></pre></pre>
<p>解决此问题的一种方法是将迭代器替换为索引</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>fn retain_even(nums: &amp;mut Vec&lt;i32&gt;) {
    let mut i = 0;
    for j in 0..nums.len() {
        if is_even(nums[j]) {
            nums[i] = nums[j];
            i += 1;
        }
    }
    nums.truncate(i);
}
<span class="boring">}
</span></code></pre></pre>
<p>但是这样就不能使用迭代器了，如果不想向代码添加索引怎么办？使用 <code>Cell</code> !</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use std::cell::Cell;
fn retain_even(nums: &amp;mut Vec&lt;i32&gt;) {
    let slice: &amp;[Cell&lt;i32&gt;] = Cell::from_mut(&amp;mut nums[..])
        .as_slice_of_cells();
    let mut i = 0;
    for num in slice.iter().filter(|num| is_even(num.get())) {
        slice[i].set(num.get());
        i += 1;
    }
    nums.truncate(i);
}
<span class="boring">}
</span></code></pre></pre>
<p>使用<code>Cell</code>后，没有了可变引用，当然就不会发生冲突了</p>
<h3 id="cell-为什么是安全的"><a class="header" href="#cell-为什么是安全的">Cell 为什么是安全的</a></h3>
<p>使用<code>Cell&lt;T&gt;</code>，你无法通过不可变的<code>Cell&lt;T&gt;</code>得到<code>&amp;T</code>与<code>&amp;mut T</code>，只能使用<code>Cell&lt;T&gt;</code>完整的去设置<code>T</code>，它是独占的，不存在其他共享引用，自然就不存在共享引用与可变引用冲突的问题，</p>
<p>如果你还不理解为什么它是安全的，那么反过来想想，为什么单线程下，不存在数据竞争，可变引用还需要是独占的？</p>
<h3 id="为什么单线程下可变引用需要是独占的"><a class="header" href="#为什么单线程下可变引用需要是独占的">为什么单线程下，可变引用需要是独占的？</a></h3>
<blockquote>
<p>参考： <a href="https://link.zhihu.com/?target=https%3A//manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/">https://manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/</a> https://www.zhihu.com/question/539001514/answer/2540415049 《Rust 深入浅出》</p>
</blockquote>
<p>下面将说明单线程下<strong>不独占可变引用</strong>造成的问题（实际编译不会成功，这里例子假设的是如果单线程下<strong>不独占可变引用</strong>）</p>
<p>问题1：导致内存不安全</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
    enum StringOrInt {
        Str(String),
        Int(i64)
    }
    use StringOrInt::{*};

    let mut x = Str(&quot;Hi!&quot;.to_string());
    let y = &amp;mut x;
    if let Str(ref insides) = x {
        *y = Int(1); // 修改 x 为 StringOrInt::Int，StringOrInt::Str 中的 String成员内存被释放，insides 指向了已经销毁的数据
        println!(&quot;x says: {}&quot;, insides); // 输出 insides，出现段错误 segmentation fault ！！
    }
}
</code></pre></pre>
<p>问题2：迭代器失效</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let mut buf = vec![1,2,3,4];
for i in &amp;buf {
    buf.push(i);
}
<span class="boring">}
</span></code></pre></pre>
<p>在上面代码中，在迭代过程中<code>push</code>，导致一直进行迭代，当<code>buf</code>的长度超过<code>cap</code>容量时，<code>vec</code> 内存将进行重分配，<code>&amp;buf</code>将指向一个无效的地址，最终导致出现段错误 segmentation fault</p>
<p>问题3：悬空指针</p>
<pre><pre class="playground"><code class="language-rust">fn main() {
    let mut vec = vec![1, 2, 3];
    let num = &amp;vec[0];
    for x in 1..100 {
        vec.push(x);
    }
    println!(&quot;{}&quot;,num);
}
</code></pre></pre>
<p>在迭代过程中，调用了 <code>vec</code> 的 <code>push</code>，当<code>buf</code>的长度超过<code>cap</code>容量时，<code>vec</code> 内存将进行重分配，<code>num</code> 成为一个悬空指针</p>
<p>以上代码都不会编译成功，因为有rust的借用检查，但是在 C、C++等语言中，就会出现问题，这也就是为什么单线程下，可变引用需要是独占的</p>
<h3 id="总结-1"><a class="header" href="#总结-1">总结</a></h3>
<ul>
<li><code>Cell</code>适合于单线程下<code>Copy</code>类型的内部可变性</li>
<li><code>Cell</code>是没有额外的开销</li>
<li><code>Cell</code>通过精心的接口设计，避免了你进行不安全的操作</li>
</ul>
<h3 id="refcell"><a class="header" href="#refcell">RefCell</a></h3>
<p>Rust 引用通过编译时借用检查来保证安全，<code>RefCell</code>则通过在运行时进行借用检查来实现内部可变性，如果发现可变借用不是独占的，将<code>panic</code>或者返回<code>Err</code></p>
<p>也就是说实际上并没有解决可变引用和引用可以共存的问题，只是将借用检查由编译器推迟到运行期</p>
<p><code>RefCell</code>的结构体也很简单</p>
<p><code>value: UnsafeCell&lt;T&gt;</code>用于去持有<code>T</code>，</p>
<p><code>borrow: Cell&lt;BorrowFlag&gt;</code>用于去记录借用的数量信息，用到了<code>Cell</code>，<code>Cell</code>用在这里刚好合适，</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>type BorrowFlag = isize;

pub struct RefCell&lt;T: ?Sized&gt; {
    borrow: Cell&lt;BorrowFlag&gt;,
    #[cfg(feature = &quot;debug_refcell&quot;)]
    borrowed_at: Cell&lt;Option&lt;&amp;'static crate::panic::Location&lt;'static&gt;&gt;&gt;, // debug 信息，仅开启 debug_refcell fetureu 时有效
    value: UnsafeCell&lt;T&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="refcell-核心方法"><a class="header" href="#refcell-核心方法">RefCell 核心方法</a></h3>
<p><code>RefCell</code> 提供 <code>borrow</code>方法进行不可变借用，<code>borrow_mut</code>方法进行可变借用</p>
<p>如果不希望在不满足借用规则时发生<code>panic</code>，可以使用<code>try_borrow</code>或者<code>try_borrow_mut</code></p>
<p><code>borrow</code>与<code>borrow_mut</code>将分别返回<code>Ref</code>与<code>RefMut</code>，当<code>Ref</code>或<code>RefMut</code>离开作用域，将取消借用</p>
<p>可变借用需要时独占的，一个<code>RefMut</code>作用域不能与另一个 <code>Ref</code>或<code>RefMut</code> 作用域发生重叠，否则将借用失败</p>
<p>用例：</p>
<pre><pre class="playground"><code class="language-rust">use std::cell::RefCell;

fn main() {
    let cell = RefCell::new(1);
    {
        let x1 = cell.borrow();
        let x2 = cell.borrow();
        println!(&quot;{}&quot;, x1);
        println!(&quot;{}&quot;, x2);
    }
    {
        let mut x = cell.borrow_mut();
        *x = 2;
    }
    let x = cell.borrow();
    println!(&quot;{}&quot;, x);

    let mut x = cell.borrow_mut(); // 发生 panic，它已经被借用了，x 还没有drop
    *x = 3;
}
</code></pre></pre>
<h3 id="refcell-是如何进行运行时借用检查"><a class="header" href="#refcell-是如何进行运行时借用检查">RefCell 是如何进行运行时借用检查？</a></h3>
<pre><code>borrow_mut`方法将检查`borrow`字段是否等于`0`，不满足条件将发生`panic`，因为可变借用必须时独占的，借用成功后`borrow`减去`1`，借用完后`borrow`字段加`1
borrow`方法将检查`borrow`字段加`1`后是否大于`0`，不满足条件将发生`panic`，这条判断实际就是检查是否已经发生了可变借用，如果已经可变借用，`borrow`字段加`1`后将是`0`，自然就不满足条件，不可变借用完后`borrow`字段减`1
</code></pre>
<h3 id="修改日志"><a class="header" href="#修改日志">修改日志</a></h3>
<ul>
<li>2023-1-13：纠正错别字，更改标题</li>
<li>2023-1-14：补充了一些说明，纠正病句，纠正修改日期</li>
<li>2023-1-14：补充<code>std</code>标准库的特殊性</li>
<li>2023-1-24：纠正错别字，调整参考链接的位置</li>
<li>2023-4-23：纠正错别字，补充一些说明</li>
</ul>
<h3 id="end"><a class="header" href="#end">End</a></h3>
<p>关于 <code>UnsafeCell</code>、<code>Cell</code>、<code>RefCell</code> 的 <code>Send</code> 与 <code>Sync</code> 的讨论可以看这篇文章：<a href="https://zhuanlan.zhihu.com/p/624194106">关于 Rust 的 Send、Sync 与 借用检测、所有权 的配合，常用类型的 Send、Sync 实现</a></p>
<blockquote>
<p>参考：
<a href="https://link.zhihu.com/?target=https%3A//manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/">https://manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/</a>
<a href="https://link.zhihu.com/?target=https%3A//course.rs/advance/smart-pointer/cell-refcell.html">https://course.rs/advance/smart-pointer/cell-refcell.html</a>
Cell 文档：<a href="https://link.zhihu.com/?target=https%3A//doc.rust-lang.org/std/cell/struct.Cell.html">https://doc.rust-lang.org/std/cell/struct.Cell.html</a>
RefCell 文档：<a href="https://link.zhihu.com/?target=https%3A//doc.rust-lang.org/std/cell/struct.RefCell.html">https://doc.rust-lang.org/std/cell/struct.RefCell.html</a>
UnsafeCell 文档：<a href="https://link.zhihu.com/?target=https%3A//doc.rust-lang.org/std/cell/struct.UnsafeCell.html">https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html</a>
《Rust 深入浅出》
封面：<a href="https://link.zhihu.com/?target=https%3A//github.com/RayMarch/ferris3d">https://github.com/RayMarch/ferris3d</a></p>
</blockquote>
<p>文章中多大知识可以在官方源码文档中获取，所以通过官方源码学习 rust 是一个很好的途径</p>
<p>如果文章内容有任何问题，你可以在评论区告诉我</p>
<blockquote>
<p>欢迎喜爱 rust 的 rustacean 加入QQ频道一起学习交流：<a href="https://link.zhihu.com/?target=https%3A//qun.qq.com/qqweb/qunpro/share%3F_wv%3D3%26_wwv%3D128%26appChannel%3Dshare%26inviteCode%3D1XRJqIu2xQD%26businessType%3D9%26jumpInfo%3DChCRorhoHUBLezzxc51XLGeBEgN2cDE%3D%26from%3D246610%26biz%3Dka%23/pc">Rust 编程语言同好，频道号：wz3qv8dszc</a></p>
</blockquote>
<p>编辑于 2023-04-23 14:12・IP 属地江西</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
